//
//  OAuthViewController.swift
//  SinaWeibo
//
//  Created by mac on 15/8/9.
//  Copyright © 2015年 mac. All rights reserved.
//

import UIKit
import SVProgressHUD

class OAuthViewController: UIViewController,UIWebViewDelegate {
    
//    MARK:------搭建界面
    private lazy var webView = UIWebView()
    
    override func loadView() {
        view = webView
        webView.delegate = self
        title = "新浪微博"
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
    }
//    关闭界面
    func close() {
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }

    override func viewDidLoad() {
                super.viewDidLoad()
//        view.backgroundColor = UIColor.whiteColor()
//        加载授权页面
        webView.loadRequest(NSURLRequest(URL: NetworkTools.shareTools.oauthURL()))
        
        
    }
//    MARK:----UIWebViewDelegate 
    func webViewDidStartLoad(webView: UIWebView) {
        
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(webView: UIWebView) {
       
        SVProgressHUD.dismiss()
    }
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
       
        let urlString = request.URL!.absoluteString
        if !urlString.hasPrefix(NetworkTools.shareTools.redirectUri){
            return true
           
        }
        if let query = request.URL?.query where query.hasPrefix("code="){
            let code = query.substringFromIndex(advance(query.startIndex, "code=".characters.count))
            loadAccessToken(code)
            
        }else{
            close()
        }
        return false

           }
    private func loadAccessToken(code:String) {
        
        NetworkTools.shareTools.loadAccessToken(code) { (result, error) -> () in
            
            if error != nil || result == nil{
             self.netError()
                return
            }
        
//            字典转模型
          UserAccount(dict: result!).loadUserInfo({ (error) -> () in
            if error != nil{
                self.netError()
                return
            }
            print("ok")
           })
        
        }
        
    }
    
/// 出错处理
    private func netError() {
        SVProgressHUD.showInfoWithStatus("你的网络不给力")
        let when = dispatch_time(DISPATCH_TIME_NOW, Int64(1 * NSEC_PER_SEC))
        dispatch_after(when, dispatch_get_main_queue()) {
            self.close()
        }
    }

}
